package com.example.service;

import com.example.entity.ChatSession;
import com.volcengine.ark.runtime.model.bot.completion.chat.BotChatCompletionRequest;
import com.volcengine.ark.runtime.model.bot.completion.chat.BotChatCompletionResult;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * DeepSeek AI服务类
 * 支持上下文管理的智能对话服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DeepSeekService {

    private final ArkService arkService;
    private final ChatSessionService chatSessionService;

    @Value("${deepseek.bot-id}")
    private String botId;

    @Value("${deepseek.api-key}")
    private String apiKey;

    /**
     * 无会话的简单对话（保持向后兼容）
     * @param userMessage 用户消息
     * @return AI回复
     */
    @Async("deepSeekTaskExecutor")
    public CompletableFuture<String> chat(String userMessage) {
        try {
            log.info("开始处理简单对话消息: {}", userMessage);
            
            List<ChatMessage> messages = new ArrayList<>();
            
            // 添加系统消息
            ChatMessage systemMessage = ChatMessage.builder()
                    .role(ChatMessageRole.SYSTEM)
                    .content("你是DeepSeek智能助手，专门为在线考试管理系统提供帮助。你可以协助用户解答关于考试创建、题目管理、成绩分析等相关问题。请以友好、专业的方式回答用户问题。")
                    .build();
            
            // 添加用户消息
            ChatMessage userChatMessage = ChatMessage.builder()
                    .role(ChatMessageRole.USER)
                    .content(userMessage)
                    .build();
            
            messages.add(systemMessage);
            messages.add(userChatMessage);

            // 发送请求并获取响应
            String response = sendChatRequest(messages);
            
            log.info("简单对话处理完成，回复长度: {}", response.length());
            return CompletableFuture.completedFuture(response);
            
        } catch (Exception e) {
            log.error("简单对话处理失败", e);
            return CompletableFuture.failedFuture(new RuntimeException("与AI助手对话时发生错误: " + e.getMessage()));
        }
    }

    /**
     * 带会话上下文的对话
     * @param userId 用户ID
     * @param sessionId 会话ID（可选，为null时使用默认会话）
     * @param userMessage 用户消息
     * @return AI回复
     */
    @Async("deepSeekTaskExecutor")
    public CompletableFuture<String> chatWithContext(Long userId, String sessionId, String userMessage) {
        try {
            log.info("开始处理带上下文的对话 - 用户: {}, 会话: {}, 消息: {}", userId, sessionId, userMessage);
            
            // 获取或创建会话
            ChatSession session;
            if (sessionId == null || sessionId.isEmpty()) {
                session = chatSessionService.getOrCreateDefaultSession(userId);
            } else {
                session = chatSessionService.getSession(userId, sessionId)
                        .orElseThrow(() -> new RuntimeException("会话不存在或已过期: " + sessionId));
            }
            
            // 添加用户消息到会话
            session = chatSessionService.addMessage(userId, session.getSessionId(), "user", userMessage);
            
            // 构建API消息列表
            List<ChatMessage> apiMessages = buildApiMessages(session);
            
            // 发送请求并获取响应
            String response = sendChatRequest(apiMessages);
            
            // 添加AI回复到会话
            chatSessionService.addMessage(userId, session.getSessionId(), "assistant", response);
            
            log.info("带上下文对话处理完成 - 会话: {}, 回复长度: {}", session.getSessionId(), response.length());
            return CompletableFuture.completedFuture(response);
            
        } catch (Exception e) {
            log.error("带上下文对话处理失败", e);
            return CompletableFuture.failedFuture(new RuntimeException("与AI助手对话时发生错误: " + e.getMessage()));
        }
    }

    /**
     * 创建新的对话会话
     * @param userId 用户ID
     * @param initialMessage 初始消息（可选）
     * @return 新会话
     */
    public ChatSession createNewSession(Long userId, String initialMessage) {
        ChatSession session = chatSessionService.createSession(userId);
        
        if (initialMessage != null && !initialMessage.trim().isEmpty()) {
            chatSessionService.addMessage(userId, session.getSessionId(), "user", initialMessage);
        }
        
        log.info("为用户 {} 创建新对话会话: {}", userId, session.getSessionId());
        return session;
    }

    /**
     * 获取用户的会话列表
     * @param userId 用户ID
     * @return 会话列表
     */
    public List<ChatSession> getUserSessions(Long userId) {
        return chatSessionService.getUserSessions(userId);
    }

    /**
     * 获取指定会话的详情
     * @param userId 用户ID
     * @param sessionId 会话ID
     * @return 会话详情
     */
    public ChatSession getSessionDetail(Long userId, String sessionId) {
        return chatSessionService.getSession(userId, sessionId)
                .orElseThrow(() -> new RuntimeException("会话不存在或已过期: " + sessionId));
    }

    /**
     * 删除会话
     * @param userId 用户ID
     * @param sessionId 会话ID
     * @return 是否删除成功
     */
    public boolean deleteSession(Long userId, String sessionId) {
        return chatSessionService.deleteSession(userId, sessionId);
    }

    /**
     * 重命名会话
     * @param userId 用户ID
     * @param sessionId 会话ID
     * @param newTitle 新标题
     * @return 是否重命名成功
     */
    public boolean renameSession(Long userId, String sessionId, String newTitle) {
        return chatSessionService.renameSession(userId, sessionId, newTitle);
    }

    /**
     * 归档会话
     * @param userId 用户ID
     * @param sessionId 会话ID
     * @return 是否归档成功
     */
    public boolean archiveSession(Long userId, String sessionId) {
        return chatSessionService.archiveSession(userId, sessionId);
    }

    /**
     * 更新会话配置
     * @param userId 用户ID
     * @param sessionId 会话ID
     * @param config 新配置
     * @return 是否更新成功
     */
    public boolean updateSessionConfig(Long userId, String sessionId, ChatSession.SessionConfig config) {
        return chatSessionService.updateSessionConfig(userId, sessionId, config);
    }

    /**
     * 构建API调用的消息列表
     * @param session 会话对象
     * @return ChatMessage列表
     */
    private List<ChatMessage> buildApiMessages(ChatSession session) {
        List<ChatMessage> apiMessages = new ArrayList<>();
        
        for (ChatSession.ChatMessage sessionMessage : session.getApiMessages()) {
            ChatMessageRole role;
            switch (sessionMessage.getRole().toLowerCase()) {
                case "system":
                    role = ChatMessageRole.SYSTEM;
                    break;
                case "user":
                    role = ChatMessageRole.USER;
                    break;
                case "assistant":
                    role = ChatMessageRole.ASSISTANT;
                    break;
                default:
                    log.warn("未知的消息角色: {}, 默认为USER", sessionMessage.getRole());
                    role = ChatMessageRole.USER;
            }
            
            ChatMessage apiMessage = ChatMessage.builder()
                    .role(role)
                    .content(sessionMessage.getContent())
                    .build();
            
            apiMessages.add(apiMessage);
        }
        
        log.debug("构建API消息列表，包含 {} 条消息", apiMessages.size());
        return apiMessages;
    }

    /**
     * 发送聊天请求到DeepSeek API
     * @param messages 消息列表
     * @return AI回复
     */
    private String sendChatRequest(List<ChatMessage> messages) {
        try {
            log.debug("发送请求到DeepSeek API，消息数量: {}", messages.size());
            log.debug("使用的Bot ID: {}", botId);
            log.debug("API Key长度: {}", apiKey != null ? apiKey.length() : 0);

            // 创建请求
            BotChatCompletionRequest chatCompletionRequest = BotChatCompletionRequest.builder()
                    .botId(botId)
                    .messages(messages)
                    .build();

            // 发送请求并获取响应
            BotChatCompletionResult result = arkService.createBotChatCompletion(chatCompletionRequest);
            
            // 提取AI的回复
            Object content = result.getChoices().get(0).getMessage().getContent();
            String response = content != null ? content.toString() : "";
            
            log.debug("成功获取AI回复，长度: {}", response.length());
            return response;
            
        } catch (Exception e) {
            log.error("调用DeepSeek API失败", e);
            throw new RuntimeException("调用AI服务失败: " + e.getMessage());
        }
    }

    /**
     * 用于清理资源
     */
    public void shutdown() {
        if (arkService != null) {
            arkService.shutdownExecutor();
        }
    }
} 